package com.mengtian_tech.tju.dataquery.api.task;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.mengtian_tech.tju.dataquery.api.service.AsyncDateService;
import com.mengtian_tech.tju.dataquery.api.service.CarDataHandleService;
import com.mengtian_tech.tju.dataquery.api.service.CarParkService;
import com.mengtian_tech.tju.dataquery.api.service.CarVisitApplyService;

@Component
public class AsyncCarApply {

	@Autowired
	CarVisitApplyService service;

	@Autowired
	CarParkService carParkService;
	
	@Autowired
	CarDataHandleService carDataHandleService;

	@Autowired
	AsyncDateService asyncDateService;
	
	/**
	 * 同步车辆备案信息，每隔1小时同步一次
	 */
	@Scheduled(cron = "0 0 */1 * * * ")
	public void run() {
		
		int total = 0;
		
		int count = service.asyncBusApply();
		while(count > 0) {
			total+=count;
			count = service.asyncBusApply();
		}
		
		count = service.asyncSchoolCarApply();
		while(count > 0) {
			total+=count;
			count = service.asyncSchoolCarApply();
		}
		
		count = service.asyncStudentCarApply();
		while(count > 0) {
			total+=count;
			count = service.asyncStudentCarApply();
		}
		
		
		count = service.asyncTeacherApply();
		while(count > 0) {
			total+=count;
			count = service.asyncTeacherApply();
		}
		
		this.asyncDateService.updateDate("01", total);
	} 
	
	/**
	 * 车辆进出同步
	 */
	@Scheduled(cron = "0 */5 * * * * ")
	public void asyncCarPark() {
		int total = 0;
		int count = carParkService.asyncCarPark();
		while(count > 0) {
			total+=count;
			count = carParkService.asyncCarPark();
		}
		
		//同步数据汇总报表
		try {
			Long lastId =  this.carDataHandleService.handleRpt(null);
			while(lastId != null) {
				lastId = this.carDataHandleService.handleRpt(lastId);
			}
		}catch (Exception e) {
			System.out.println("asyncCarPark rpt error:"+e.getMessage());
		}
		
		//同步用户类型
		try {
			Long lastId =  this.carDataHandleService.handleUserType(null);
			while(lastId != null) {
				lastId = this.carDataHandleService.handleUserType(lastId);
			}
		}catch (Exception e) {
			System.out.println("asyncCarPark handleUserType error:"+e.getMessage());
		}
		this.asyncDateService.updateDate("04", total);
	}
	
	/**
	 * 车辆备注状态同步
	 */
	@Scheduled(cron = "0 */10 * * * * ")
	public void asyncApplyState() {
		this.service.asyncApplyState();		
	}
	
	/**
	 * 车辆出场日期同步
	 */
	@Scheduled(cron = "0 0 0 * * * ")
	//@Scheduled(cron = "0 22 12 * * * ")
	public void asyncOutTime() {
		//更新下出场日期，表示任务执行了即可
		this.asyncDateService.updateDate("06", 0);
		
		try {
			Long lastId = this.carParkService.doAsyncOutTime(null);		
			
			while(lastId != null) {
				lastId = this.carParkService.doAsyncOutTime(lastId);
			}
		}catch (Exception e) {
			System.out.println(new Date()+"sync out time error:"+e.getMessage());
		}
		
		
		//更新下出场日期，表示任务执行了即可
		this.asyncDateService.updateDate("06", 0);
				
		
	}
	
}
